<style>
    .dialog-button {
        text-align: center;
    }
    .add_role_table{
        margin: 15px auto;
    }
    .add_role_table tr{
        line-height: 45px;
    }
</style>
<div class="easyui-layout" data-options="fit:true">
    <div data-options="region:'center',border:false">
        <!-- Begin of toolbar -->
        <div id="Role-toolbar">
            <div class="wu-toolbar-button">
                <a href="#" class="easyui-linkbutton" iconCls="icon-add" id="editRole" onclick="openaddrole(-1)"
                   plain="true">添加</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-reload" onclick="searchRoleGrid()"
                   plain="true">刷新</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-back" onclick="removeTab()" plain="true">返回</a>
            </div>
            <div class="wu-toolbar-search">
                <label>角色名称：</label><input class="easyui-textbox" type="text" name="role"
                                           data-options="prompt:'角色名称'" style="width:240px"></input>
                <a href="#" class="easyui-linkbutton" iconCls="icon-search" id="queryrole" onclick="searchRoleGrid()">开始检索</a>
            </div>
        </div>
        <!-- End of toolbar -->
        <table id="Role-datagrid" toolbar="#Role-toolbar" class="easyui-datagrid">
        </table>
    </div>
</div>
<!-- Begin of easyui-dialog -->
<div id="role-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'"
     style="width:400px; padding:10px;">
    <form id="role-add-form" method="post">
        <table class="add_role_table">
            <tr>
                <td width="100px">角色名称:</td>
                <td>
                    <input class="easyui-textbox" type="text" name="rolename" data-options="prompt:'角色名称'" style="width:240px;height:25px;"></input>
                </td>
            </tr>
            <tr>
                <td>角色描述:</td>
                <td>
                    <input class="easyui-textbox" data-options="multiline:true,prompt:'角色描述'" name="roledesc"
                           style="width:280px;height:120px"></input>
                </td>
            </tr>
        </table>
    </form>
</div>
<!-- End of easyui-dialog -->
<!-- Begin of easyui-dialog -->
<div id="auth-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'"
     style="width:400px;overflow:auto;height:500px;padding:10px;">
    <ul id="authTree">
    </ul>
</div>
<!-- End of easyui-dialog -->
<script type="text/javascript">
    var editRole_id = '';
    var authData;
    var role_id;
    var eventNode;
    $(function () {
        $('#Role-datagrid').datagrid({
            url: getRoleListByPageUrl,
            rownumbers: true,
            pagination: true,
            fitColumns: true,
            fit: true,
            pageSize: 10,
            pageList: [5, 20, 50],
            remoteSort: true,
            singleSelect: true,
            multiSort: true,
            columns: [[
                {field: 'id', title: 'ID', align: 'center', width: 60},
                {field: 'role_name', title: '角色名称', width: 100, align: 'center'},
                {field: 'auth_ids', title: '权限', hidden: 'true'},
                {field: 'role_desc', title: '角色描述', width: 180, align: 'center'},
                {field: 'operation', title: '操作', width: 180, align: 'center', formatter: showRoleOptBtn}
            ]],
            queryParams: {
                rolename: ""
            },
            onLoadSuccess: function (data) {
                $("a[name='editRole']").linkbutton({plain: true, iconCls: 'icon-edit'});
                $("a[name='disAuth']").linkbutton({plain: true, iconCls: 'icon-sum'});
            }
        });
    });
    function searchRoleGrid() {
        var queryParams = $('#Role-datagrid').datagrid('options').queryParams;
        queryParams.rolename = $.trim($('input[textboxname=role]').textbox('getValue'));
        $('#Role-datagrid').datagrid('reload');
    }
    function showRoleOptBtn(value, row, index) {
        return "<a href='#' onclick='editRole(" + index + ")' class='easyui-linkbutton' id='editRole' name='editRole'>编辑</a>&nbsp;" +
            "<a href='#' onclick='disAuth(" + index + ")' class='easyui-linkbutton' id='disAuth' name='disAuth'>分配权限</a>";
    }
    /**
     *     打开角色编辑窗口
     */
    function openaddrole(roleid) {
        $('#role-add-form').form('clear');
        role_id = roleid;
        $('#role-dialog').dialog({
            closed: false,
            modal: true,
            title: "添加角色",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: doSaveRole
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#role-dialog').dialog('close');
                }
            }]
        });
    }
    function editRole(rowIndex) {
        rows = $('#Role-datagrid').datagrid('getSelections');
        if (rows.length != 1) {
            return;
        }
        //获取当前选中行的索引
        selectedRowIndex = $('#Role-datagrid').datagrid('getRowIndex', $('#Role-datagrid').datagrid('getSelected'));
        //判断当前按钮所在行与当前选中行是否一致
        if (rowIndex == selectedRowIndex) {
            row = $('#Role-datagrid').datagrid('getSelected');
            if (row) {
                role_id = row['id'];
                $('input[textboxname=rolename]').textbox('setValue', row['role_name']);
                $('input[textboxname=roledesc]').textbox('setValue', row['role_desc']);
                $('#role-dialog').dialog({
                    closed: false,
                    modal: true,
                    title: "编辑角色",
                    top: 30,
                    buttons: [{
                        text: '确定',
                        iconCls: 'icon-ok',
                        handler: doSaveRole
                    }, {
                        text: '取消',
                        iconCls: 'icon-cancel',
                        handler: function () {
                            $('#role-dialog').dialog('close');
                        }
                    }]
                });
            }
        }
    }
    function doSaveRole(){
        if($.trim($('input[textboxname=rolename]').textbox('getValue'))==""){
            $.messager.show({
                title:'系统提示',
                msg:"角色名称没有填写"
            });
            $('input[textboxname=rolename]').textbox().next('span').find('input').focus();
            return;
        }
        var rolemsg,isExistRole;
        $.ajax({
            url: checkRoleNameUrl,
            type: "post",
            async: false,
            dataType: "json",
            data: 'id='+role_id+'&rolename=' + $.trim($('input[textboxname=rolename]').textbox('getValue')),
            success: function (result) {
                rolemsg = result.msg;
                isExistRole = result.isExist;
            }, error: function () {
            }
        });
        if(isExistRole){
            $.messager.show({
                title:'系统提示',
                msg:rolemsg
            });
            $('input[textboxname=rolename]').textbox().next('span').find('input').focus();
            return;
        }
        $("#role-add-form").ajaxSubmit({
            url: doSaveRoleUrl,
            type: "post",
            dataType: "json",
            beforeSubmit: function (arr, $form, options) {
                arr.push({'name':'id','value':role_id,'type':'hidden','required':false});
            },
            //提交成功后的回调函数
            success: function (result, status, xhr, $form) {
                $.messager.show({
                    title:'系统提示',
                    msg:result.msg,
                    timeout:500,
                    showType:'slide'
                });
                if(result.errorCode == 0){
                    if(role_id==-1){
                        $('input[textboxname=rolename]').textbox('setValue','');
                        $('input[textboxname=roledesc]').textbox('setValue','');
                        $('input[textboxname=rolename]').textbox().next('span').find('input').focus();
                        $('#Role-datagrid').datagrid('reload');
                    }else{
                        $('#Role-datagrid').datagrid('reload');
                        $('#role-dialog').dialog('close');
                    }
                }
            },
            error: function (xhr, status, error, $form) {
            },
            complete: function (xhr, status, $form) {
            }
        });
    }
    function setNodeChecked(auth_ids){
        if (auth_ids == null){
            auth_ids = '';
        }
        var ids = auth_ids.split(',');
        //获取树的所有节点
        var nodes  =$('#authTree').tree('getChildren');
        for(i=0;i<nodes.length;i++){
            //只判断叶子节点有没有权限
            if($('#authTree').tree('isLeaf',nodes[i].target)){
                if($.inArray(nodes[i].id, ids)!=-1){
                    $('#authTree').tree('check', nodes[i].target);
                }
            }
        }
    }
    function disAuth(rowIndex) {
        rows = $('#Role-datagrid').datagrid('getSelections');
        if (rows.length != 1) {
            return;
        }
        //获取当前选中行的索引
        selectedRowIndex = $('#Role-datagrid').datagrid('getRowIndex', $('#Role-datagrid').datagrid('getSelected'));
        //判断当前按钮所在行与当前选中行是否一致
        if (rowIndex == selectedRowIndex) {
            row = $('#Role-datagrid').datagrid('getSelected');
            if (row) {
                editRole_id = row['id'];
                $.ajax({
                    url: getAllMenuUrl,
                    type: 'post',
                    datatype: 'json',
                    async: false,
                    success: function (result) {
                        authData = InitTreeData(result);
                    }
                });
                $("#authTree").tree({
                    data: authData,
                    lines: false,
                    checkbox: true,
                    cascadeCheck: false,
                    onCheck: function (node, checked) {
                        var tree = $('#authTree');
                        if (!eventNode) {
                            //鼠标勾选事件初始化标致，标识鼠标勾选事件第一次遍历开始
                            eventNode = node;
                            //将鼠标勾选时的节点保存起来，待向下 遍历时，将从此节点开始
                            treeup = true;
                            //向上遍历标志，由鼠标勾选的节点eventNode开始向上遍历
                        }
                        if (treeup) {
                            //向上遍历
                            var ParentNode = tree.tree("getParent", node.target);
                            if (ParentNode) {
                                //存在上级节点
                                if (checked)
                                    //如果是选择
                                    tree.tree("check", ParentNode.target);
                                //选中上级节点。注意：如果父节点之前未选中，执行此行代码后，会再次触发onCheck事件，下面的代码暂时不会被执行；如果之前兄弟节点已被选中，那么上级节点也被选中，此行代码执行后不会触发onCheck事件，而直接执行下面的代码
                                else {
                                    //如果是取消选择
                                    var isCheck = false;
                                    var childNode = tree.tree("getLeafChildren", ParentNode.target);
                                    for (var i = 0; i < childNode.length; i++) {
                                        //循环当前节点的父节点的所有子节点，及包含当前节点的所有兄弟节点
                                        if (childNode[i].checked) {
                                            isCheck = true;
                                            //只要有兄弟节点被选中，则退出循环
                                            break;
                                        }
                                    }
                                    if (!isCheck)
                                        //如果所有兄弟节点及当前节点都未勾选，则取消父节点的勾选
                                        tree.tree("uncheck", ParentNode.target);
                                }
                            }
                            treeup = false;
                            //向上遍历结束
                        }
                        //到达根部节点或向上遍历结束之后再回到原始节点开始向下遍历
                        if (!treeup && eventNode) {
                            var childNode = tree.tree("getChildren", eventNode.target);
                            //获取原始节点eventNode的所有子孙节点
                            if (checked) {
                                //如果是选择
                                for (var i = 0; i < childNode.length; i++) {
                                    //循环所有子孙节点，全部选中
                                    tree.tree("check", childNode[i].target);
                                }
                            }
                            else {
                                //如果是取消
                                for (var i = 0; i < childNode.length; i++) {
                                    //循环所有子孙节点，全部取消勾选
                                    tree.tree("uncheck", childNode[i].target);
                                }
                            }
                        }
                        eventNode = null;
                        //标志本次鼠标勾选事件遍历结束
                    }
                });
                setNodeChecked(row['auth_ids']);
                $('#auth-dialog').dialog({
                    closed: false,
                    modal: true,
                    title: "分配权限",
                    top: 30,
                    buttons: [{
                        text: '确定',
                        iconCls: 'icon-ok',
                        handler: doDisAuth
                    }, {
                        text: '取消',
                        iconCls: 'icon-cancel',
                        handler: function () {
                            $('#auth-dialog').dialog('close');
                        }
                    }]
                });
            }
        }
    }
    function doDisAuth() {
        arr_ids = [];
        arr_desc = [];
        var checkeds = $('#authTree').tree('getChecked', 'checked');
        for (var i = 0; i < checkeds.length; i++) {
            arr_ids.push(checkeds[i].id);
            if(checkeds[i].attributes.module!= null && checkeds[i].attributes.module!= ''
                && checkeds[i].attributes.controller != null && checkeds[i].attributes.controller != ''
                && checkeds[i].attributes.method != null && checkeds[i].attributes.method != ''
            ){
                arr_desc.push(checkeds[i].attributes.module+'-'+checkeds[i].attributes.controller+'-'+checkeds[i].attributes.method);
            }
        }
        $.ajax({
            url: doDisAuthUrl,
            type: 'post',
            datatype: 'json',
            async: false,
            data:'id='+ editRole_id + '&auth_ids='+arr_ids.join(',')+'&auth_desc='+arr_desc.join(','),
            success: function (result) {
                $.messager.show({
                    title: '系统提示',
                    msg: result.msg
                });
                if(result.errorCode == 0){
                    $('#auth-dialog').dialog('close');
                    $('#Role-datagrid').datagrid('reload');
                }
            }
        });
    }
</script>